package com.base.system.managedBean.baseBean;

import java.io.Serializable;

import org.operamasks.faces.annotation.Accessible;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.Validate;
import org.operamasks.faces.component.form.impl.UITextField;

import com.base.commons.SpringBeanHolder;
import com.base.security.SecurityConst;
import com.base.security.entity.SecurityRole;
import com.base.security.service.SecurityEntityManager;

public class BaseSecurityRoleBean implements Serializable {
	protected SecurityEntityManager securityEntityManager = SpringBeanHolder
			.getBean("securityEntityManager");
	@Accessible
	@Bind(id = "id", attribute = "binding")
	protected UITextField id;
	@Bind(id = "rolename", attribute = "value")
	protected String rolename;
	@Bind(id = "displayName", attribute = "value")
	protected String displayName;
	@Bind(id = "description", attribute = "value")
	protected String description;
	@Bind(id = "roleType", attribute = "value")
	protected String roleType;
	@Accessible
	protected String roleId;
	protected SecurityRole securityRole;

	protected void setSecurityRoleProperty() {
		if (securityRole == null)
			return;
		if (id != null)
			securityRole.setId(Integer.parseInt(id.getValue().toString()));
		securityRole.setDescription(description);
		securityRole.setDisplayName(displayName);
		securityRole.setRolename(rolename);
		securityRole.setRoleType(SecurityConst.ROLETYPE_USER);
	}

	protected void getSecurityRoleProperty() {
		if (securityRole == null)
			return;
		if (id != null)
			id.setValue(securityRole.getId().toString());
		roleId = securityRole.getId().toString();
		String tempRolename = securityRole.getRolename();
		rolename = tempRolename.substring(tempRolename
				.indexOf(SecurityRole.ROLE_PRIFIX) + 5);
		displayName = securityRole.getDisplayName();
		description = securityRole.getDescription();
		roleType = securityRole.getRoleType();
	}

	@Validate(id = { "rolename" }, message = "角色代码已存在，请您选择其他角色代码！")
	public boolean validateRolename(String name) {
		// System.out.println("得到的userName is:" + name);
		// 如果roleid不为空，则说明是编辑，判断角色是否变，如果不变，则检验通过。如果变化了，再执行查重判断
		if (id != null && !"".equals(id.getSubmittedValue())) {
			// System.out.println("得到的userId is:" + userId);
			// System.out.println("得到的userId value is:"+
			// userId.getSubmittedValue());
			SecurityRole roleById = securityEntityManager.getRoleById(Integer
					.parseInt(id.getValue().toString()));
			if (roleById != null
					&& roleById.getRolename().equals(
							SecurityRole.ROLE_PRIFIX + name))
				return true;
		}
		SecurityRole sr = securityEntityManager
				.getRoleByValue(SecurityRole.ROLE_PRIFIX + name);
		if (sr == null)
			return true;
		else
			return false;
	}
}
